package com.zzy.jwt.jwtfilter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzy.jwt.pojo.User;
import com.zzy.jwt.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Lucas-zhang
 * @description TODO
 * @date 2022-03-22 17:38
 */
public class JWTAuthenticationRequestFilter extends OncePerRequestFilter {

    private UserDetailsService userDetailsService;

    public JWTAuthenticationRequestFilter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 校验Token
        Authentication authentication = getAuthentication(request);
        if (authentication == null) {
            filterChain.doFilter(request, response);
            return;
        }
        // 认证成功, 保存到SecurityContext上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }

    private Authentication getAuthentication(HttpServletRequest request) throws JsonProcessingException {
        // 判断是否有Token，拿到Token
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Bearer ")) {
            return null;
        }
        String token = header.split(" ")[1];
        // 通过Token解析
        Claims claims = JWTUtil.parse(token);
        if (claims == null) {
            return null;
        }
        User user = (User) new ObjectMapper().readValue(claims.getSubject(), User.class);

        // 开始验证
        // 通过用户名查找数据库，确认是否存在该用户
        UserDetails userDetails = null;
        try {
            userDetails = userDetailsService.loadUserByUsername(user.getUsername());
        } catch (UsernameNotFoundException e) {
            return null;
        }

        // 校验Token的密码与数据库中用户密码是否一致
        if (!userDetails.getPassword().equals(user.getPassword())) {
            return null;
        }
        // 构造Authentication对象
        return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
    }
}
